$(() => {
    template.defaults.imports.moment = moment
    const user = JSON.parse(sessionStorage.getItem('user'))
    $('#avatarPreview').attr('src', user.avatar)
    $('#nickName').html(user.nickName)

    //根据id获取文章信息
    const id = location.search.split('=')[1]
    $.ajax({
        type: 'get',
        url: `/posts/${id}`,
        success(data) {
            $('#formBox').html(template('formTPL', data))
            //获取下拉框数据
            $.ajax({
                type: 'get',
                url: '/categories',
                success(res) {
                    const html = template('selectTPL', { data: res })
                    $('#category').html(html)
                    $('#category').val(data.category)
                },
                error() {
                    alert('获取分类数据失败!')
                }
            })

        },
        error() {
            alert('获取文章信息失败!')
        }
    })

    //图片上传
    $('#formBox').on('change', '#feature', function () {
        const formdata = new FormData()
        formdata.append('avatar', this.files[0])
        $.ajax({
            type: 'post',
            url: '/upload',
            data: formdata,
            processData: false,
            contentType: false,
            success(res) {
                $('#preview').attr('src', res[0].avatar)
                $('#hiddenInput').val(res[0].avatar)
            }
        })
    })

    //编辑表单提交
    $('#formBox').on('submit', '#editArticleForm', function (e) {
        const data = $(this).serialize()
        const articleId = e.target.dataset.id

        $.ajax({
            type: 'put',
            url: `/posts/${articleId}`,
            data: data,
            success() {
                alert('修改成功!')
                location.href = '/admin/posts.html'
            },
            error() {
                alert('修改失败!')
            }
        })
        return false
    })

})